<style scoped>
</style>
<template>
  <div>
    <Modal v-model="IsModalShow"
           :title="modalFormTitle"
           :mask-closable="false"
           @on-cancel="cancel"
           width="1000">
      <Tabs value="name1">
        <TabPane label="基本信息"
                 name="name1">
          <Form ref="modalForm"
                :model="modalForm"
                :label-width="120"
                value="true"
                style="padding: 3px 60px">
            <Row>
              <Col span="12">
              <Form-item label="商铺名称"
                         prop="shopName"
                         :rules="{required: true, message: '必填', trigger:'blur',type:'string'}">
                <Input v-model="modalForm.shopName"></Input>
              </Form-item>
              <Form-item label="所属场所"
                         prop="shopPlace"
                         :rules="{required: true, message: '必填', trigger:'blur',type:'number'}">
                <Select v-model="modalForm.shopPlace">
                  <Option v-for="item in placeList"
                          :value="item.value"
                          :key="item.value">{{ item.label }}</Option>
                </Select>
              </Form-item>
              <Form-item label="地址"
                         prop="addr"
                         :rules="{required: true, message: '必填', trigger:'blur',type:'string'}">
                <Input v-model="modalForm.addr"></Input>
              </Form-item>

              <Form-item label="负责人姓名"
                         prop="managerName"
                         :rules="{required: true, message: '必填', trigger:'blur',type:'string'}">
                <Input v-model="modalForm.managerName"></Input>
              </Form-item>

              <Form-item label="负责人电话"
                         prop="managerMobile"
                         :rules="{required: true, message: '输入11位手机号', trigger:'blur',type:'string',pattern: /^1\d{10}$/}">
                <Input v-model="modalForm.managerMobile"></Input>
              </Form-item>
              <Form-item label="所属部门"
                         prop="cascader"
                         :rules="{required: true, message: '必选', trigger:'change', type:'array'}">
                <Cascader :data="deptCascader"
                          v-model="modalForm.cascader"
                          :filterable="true"
                          change-on-select
                          transfer
                          placeholder="选择部门"></Cascader>
              </Form-item>
              <Form-item label="微信名称"
                         prop="wxName">
                <Input v-model="modalForm.wxName"
                       :readonly="true"></Input>
              </Form-item>
              <Form-item label="商铺平面图">
                <div class="demo-upload-list"
                     v-if="modalForm.shopMap">
                  <img :src="baseServerUrl+modalForm.shopMap" />
                  <div class="demo-upload-list-cover">
                    <Icon type="ios-eye-outline"
                          @click.native="handleView"></Icon>
                    <Icon type="ios-trash-outline"
                          @click.native="handleRemove"></Icon>
                  </div>
                </div>
                <Upload v-else
                        ref="upload"
                        :headers="MyHeaders"
                        :before-upload="beforeUpload"
                        :on-success="handleSuccess"
                        :format="['jpg','png']"
                        :on-format-error="handleFormatError"
                        :action="UploadAddress"
                        :data="{shopId:uploadShopId}"
                        style="display: inline-block;width:58px;    border: 1px dashed #dcdee2;
    border-radius: 4px;
    text-align: center;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: border-color .2s ease;">
                  <div style="width: 58px;height:58px;line-height: 58px;">
                    <Icon type="ios-camera"
                          size="20"></Icon>
                  </div>
                </Upload>
                <Modal title="商铺平面图"
                       v-model="imgVisble">
                  <img :src="baseServerUrl+modalForm.shopMap"
                       v-if="imgVisble"
                       style="width: 100%">
                </Modal>
              </Form-item>
              <Form-item label="微信头像"
                         prop="wxImage">
                <img :src="modalForm.wxImage"
                     style="width:50px" />
              </Form-item>
              <Form-item label="责任书"
                         prop="dutyLetter">
                <div class="handle-img-wrapper"
                     v-if="modalForm.dutyLetter">
                  <img :src="baseServerUrl+'/'+modalForm.dutyLetter"
                       style="width:50px" />
                  <div class="img-cover">
                    <Icon type="ios-trash-outline"
                          @click.native="handleRemoveDutyLetter"></Icon>
                  </div>
                </div>
              </Form-item>
              <Form-item label="店铺照片"
                         prop="picture">
                <div class="handle-img-wrapper"
                     v-if="modalForm.picture">
                  <img :src="baseServerUrl+'/'+modalForm.picture"
                       style="width:50px" />
                  <div class="img-cover">
                    <Icon type="ios-trash-outline"
                          @click.native="handleRemovePicture"></Icon>
                  </div>
                </div>
              </Form-item>
              </Col>
              <Col span="11"
                   offset="1">
              <Input v-model="addrSearchVal"
                     element-id="tipinput">
              <span slot="prepend">请输入地址</span>
              <Button slot="append"
                      icon="ios-search"
                      @click="searchAddr"></Button>
              </Input>
              <div style="position:relative;margin-bottom:10px;margin-top:10px;">
                <div id="map-container"></div>
                <div id="mapShade"
                     :style="{'display':mapShadeShow?'block':'none'}"></div>
              </div>

              <Row>
                <Col span="10">
                <Form-item label="纬度"
                           label-width="60">
                  <Input v-model="modalForm.lat"></Input>
                </Form-item>
                </Col>
                <Col span="10">
                <Form-item label="经度"
                           label-width="60">
                  <Input v-model="modalForm.lng"></Input>
                </Form-item>
                </Col>
                <Col span="3"
                     offset="1">
                <Button type="warning"
                        :loading="modalForm_loading"
                        @click="startLocate">设置地址</Button>
                </Col>
              </Row>
              </Col>
            </Row>
          </Form>
        </TabPane>
        <TabPane label="紧急联系人"
                 name="name2">
          <div style="padding:10px 100px;">
            <Row style="padding:10px 50px;">
              <Button type="warning"
                      icon="plus-round"
                      @click="addNotifier">添加紧急联系人</Button>
            </Row>

            <Form :model="formItem"
                  :label-width="50">
              <div v-if="alarmNotifierList.length>0">
                <Row v-for="(item,index) in alarmNotifierList"
                     :key="index">
                  <Col span="12">
                  <FormItem label="姓名">
                    <Input v-model="item.name"></Input>
                  </FormItem>
                  </Col>
                  <Col span="12">
                  <FormItem label="电话">
                    <Input v-model="item.phone"></Input>
                  </FormItem>
                  </Col>
                </Row>
              </div>
            </Form>
          </div>
        </TabPane>
      </Tabs>

      <div slot="footer">
        <Button type="default"
                @click="cancel">关闭</Button>
        <Button type="primary"
                :loading="modalForm_loading"
                @click="saveForm('modalForm')">保存</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import { saveShop, updateShop } from '@/api/asset'
import { getDeptCascader } from '@/api/system'
import config from '@/config'

const baseUrl =
  process.env.NODE_ENV === 'development'
    ? config.baseUrl.dev
    : config.baseUrl.pro
export default {
  props: {
    parentForm: {
      type: Object,
      default: function() {
        return {
          id: '',
          name: '',
          addr: '',
          managerName: '',
          managerMobile: '',
          dutyLetter: '',
          cascader: []
        }
      }
    },
    modalShow: {
      type: Boolean,
      default: true
    },
    modalFormTitle: {
      type: String,
      default: '添加商铺'
    }
  },
  data() {
    return {
      imgVisble: false,
      uploadShopId: 0,
      IsUploading: false,
      IsModalShow: false,
      modalForm: {},
      modalForm_loading: false,
      deptCascader: [],
      baseServerUrl: baseUrl,
      map: null,
      mousetool: null,
      mapShadeShow: false,
      addrSearchVal: '',
      alarmNotifierList: [],
      placeList: [
        {
          value: 1,
          label: '学校'
        },
        {
          value: 2,
          label: '医院/诊所'
        },
        {
          value: 3,
          label: '商店/超市'
        },
        {
          value: 4,
          label: '餐饮场所'
        },
        {
          value: 5,
          label: '宾馆/旅馆'
        },
        {
          value: 6,
          label: '娱乐/休闲场所'
        },
        {
          value: 7,
          label: '网吧'
        },
        {
          value: 8,
          label: '美容/美发/洗浴场所'
        },
        {
          value: 9,
          label: '生产/加工企业'
        },
        {
          value: 11,
          label: '消防栓'
        },
        {
          value: 12,
          label: '微型消防站'
        },
        {
          value: 13,
          label: '医疗服务站'
        },
        {
          value: 14,
          label: '消防支队'
        },
        {
          value: 10,
          label: '其他'
        }
      ]
    }
  },
  watch: {
    modalShow(curVal, oldVal) {
      if (curVal) {
        this.modalForm = JSON.parse(JSON.stringify(this.parentForm))
        if (this.parentForm.cascader) {
          this.modalForm.cascader = this.parentForm.cascader
            .split(',')
            .map(function(item) {
              return parseInt(item)
            })
        } else {
          this.modalForm.cascader = []
        }
        this.addrSearchVal = ''

        this.addMarker(this.modalForm.lng, this.modalForm.lat)

        if (this.modalForm.alarmNotifier) {
          let alarmNotifier = this.modalForm.alarmNotifier
          let notifierArr = []
          alarmNotifier.split('|').forEach(item => {
            let name = item.split(',')[0]
            let phone = item.split(',')[1]
            notifierArr.push({ name: name, phone, phone })
          })
          this.alarmNotifierList = notifierArr
        } else {
          this.alarmNotifierList = []
        }
        console.log(this.modalForm)
        this.uploadShopId = this.modalForm.shopId
      }
      this.IsModalShow = curVal
    }
  },
  computed: {
    MyHeaders: function() {
      let myHeaders = {}
      let tokenValue = sessionStorage.getItem('token')
      if (tokenValue) {
        myHeaders.token = tokenValue
      }
      return myHeaders
    },
    UploadAddress: function() {
      return baseUrl + '/bss/shop/shop_map'
    }
  },
  created() {},
  mounted() {
    this.getDeptCascader()
    this.$nextTick(() => {
      this.initMap()
    })
  },
  methods: {
    beforeUpload() {
      this.IsUploading = true
    },
    handleSuccess(res, file) {
      this.IsUploading = false
      let result = res
      if (res.code == 0) {
        this.$Message.success('上传成功！')
        this.$emit('refreshTableList')
        this.modalForm.shopMap = res.data
      } else {
        this.$Message.error(res.msg)
      }

      console.log(result)
    },
    handleFormatError(file) {
      this.IsUploading = false
      this.$Notice.warning({
        title: '文件格式不对',
        desc: '上传文件格式不正确，请上传xls或xlsx格式的excel'
      })
    },
    handleView() {
      this.imgVisble = true
    },
    handleRemove() {
      this.modalForm.shopMap = ''
    },
    cancel() {
      this.$emit('listenModalForm')
    },
    async getDeptCascader() {
      let res = await getDeptCascader()
      if (res.code == 0) {
        this.deptCascader = res.data
      }
    },
    saveForm(name) {
      this.$refs[name].validate(async valid => {
        if (valid) {
          this.modalForm_loading = true
          let params = JSON.parse(JSON.stringify(this.modalForm))
          let arr = this.modalForm.cascader
          params.deptId = arr[arr.length - 1]
          params.cascader = arr.join(',')
          if (this.alarmNotifierList.length > 0) {
            params.alarmNotifier = this.alarmNotifierList
              .filter(val => val.name && val.phone)
              .map(item => {
                return item.name + ',' + item.phone
              })
              .join('|')
          }
          try {
            let result
            if (params.shopId) {
              result = await updateShop(params)
            } else {
              result = await saveShop(params)
            }

            if (result.code == 0) {
              this.$Message.success('提交成功!')
              this.$emit('listenModalForm')
              this.$emit('refreshTableList')
            } else {
              this.$Message.error(result.msg)
            }
          } catch (err) {
            console.log(err)
            this.$Message.error('服务器异常，稍后再试')
          }
          this.modalForm_loading = false
        } else {
          this.$Message.error('表单验证失败!')
        }
      })
    },
    initMap() {
      var _this = this
      this.map = new AMap.Map('map-container', {
        resizeEnable: true,
        scrollWheel: true,
        zoom: 18
      })

      this.map.plugin(['AMap.MouseTool'], function() {
        //鼠标工具插件
        _this.mousetool = new AMap.MouseTool(_this.map)
      })

      AMap.event.addListener(_this.mousetool, 'draw', function(e) {
        var drawObj = e.obj
        var point = drawObj.getPosition()
        _this.modalForm.lat = point.lat
        _this.modalForm.lng = point.lng
        _this.mapShadeShow = false
        _this.mapShadeShow = false
        _this.mousetool.close(false)
      })

      AMap.plugin('AMap.Autocomplete', function() {
        // 实例化Autocomplete
        var autoOptions = {
          // input 为绑定输入提示功能的input的DOM ID
          input: 'tipinput'
        }
        var autoComplete = new AMap.Autocomplete(autoOptions)
        // 无需再手动执行search方法，autoComplete会根据传入input对应的DOM动态触发search
        AMap.event.addListener(autoComplete, 'select', function(data) {
          //TODO 选择后的处理程序，data的格式见 附录
          console.log(data)
          if (data.poi.address.length > 0) {
            _this.addrSearchVal =
              data.poi.district + data.poi.address + data.poi.name
          } else {
            _this.addrSearchVal = data.poi.district + data.poi.name
          }
          let location = data.poi.location
          if (location) {
            _this.addMarker(location.lng, location.lat)
            _this.modalForm.lat = location.lat
            _this.modalForm.lng = location.lng
          }
        })
      })
    },
    searchAddr() {
      var addr = this.addrSearchVal
      let _this = this
      AMap.plugin('AMap.Geocoder', function() {
        var geocoder = new AMap.Geocoder({
          // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
        })

        geocoder.getLocation(addr, function(status, result) {
          if (status === 'complete' && result.info === 'OK') {
            // result中对应详细地理坐标信息
            var location = result.geocodes[0].location
            try {
              if (location) {
                _this.addMarker(location.lng, location.lat)
                _this.modalForm.lat = location.lat
                _this.modalForm.lng = location.lng
              } else {
                _this.$Message.error('未查询到地理信息!')
              }
            } catch (error) {
              _this.$Message.error('查询地理信息失败,请检查网络!')
            }
          } else {
            _this.$Message.error('未查询到地理信息!')
          }
        })
      })
    },
    addMarker(lng, lat) {
      this.map.clearMap()
      if (lat && lng) {
        var marker = new AMap.Marker({
          position: [lng, lat]
        })
        marker.setMap(this.map)
        this.map.setFitView()
      }
    },
    startLocate() {
      this.map.clearMap()
      this.mapShadeShow = true
      this.mousetool.marker({ offset: new AMap.Pixel(-14, -11) })
    },
    addNotifier() {
      if (this.alarmNotifierList.length < 8) {
        this.alarmNotifierList.push({ name: '', phone: '' })
      }
    },
    handleRemoveDutyLetter() {
      this.modalForm.dutyLetter = ''
    },
    handleRemovePicture() {
      this.modalForm.picture = ''
    }
  }
}
</script>
<style lang="less" scoped>
#map-container {
  width: 100%;
  height: 380px;
}
#mapShade {
  width: 100%;
  height: 380px;
  background-color: #000000;
  position: absolute;
  opacity: 0.35;
  left: 0;
  top: 0;
  z-index: 100;
  -webkit-pointer-events: none;
  -moz-pointer-events: none;
  -ms-pointer-events: none;
  -o-pointer-events: none;
  pointer-events: none;
}
.btn {
  display: inline-block;
  font-weight: 400;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  border: 1px solid transparent;
  transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out,
    border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
  background-color: transparent;
  background-image: none;
  color: #25a5f7;
  border-color: #25a5f7;
  padding: 0.25rem 0.5rem;
  line-height: 1.5;
  border-radius: 1rem;
  -webkit-appearance: button;
  cursor: pointer;
}

.btn:hover {
  color: #fff;
  background-color: #25a5f7;
  border-color: #25a5f7;
}

.btn:hover {
  text-decoration: none;
}

.input-item {
  position: relative;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
  -ms-flex-align: center;
  align-items: center;
  width: 100%;
  height: 3rem;
}

.input-item:last-child {
  margin-bottom: 0;
}

.input-item > select,
.input-item > input[type='text'],
.input-item > input[type='date'] {
  position: relative;
  -ms-flex: 1 1 auto;
  flex: 1 1 auto;
  width: 1%;
  margin-bottom: 0;
}

.input-item > select:not(:last-child),
.input-item > input[type='text']:not(:last-child),
.input-item > input[type='date']:not(:last-child) {
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
}

.input-item > select:not(:first-child),
.input-item > input[type='text']:not(:first-child),
.input-item > input[type='date']:not(:first-child) {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}

.input-item-prepend {
  margin-right: -1px;
}

.input-item-text,
input[type='text'],
input[type='date'],
select {
  height: calc(2.2rem + 2px);
}

.input-item-text {
  width: 6rem;
  text-align: justify;
  padding: 0.4rem 0.7rem;
  display: inline-block;
  text-justify: distribute-all-lines;
  /*ie6-8*/
  text-align-last: justify;
  /* ie9*/
  -moz-text-align-last: justify;
  /*ff*/
  -webkit-text-align-last: justify;
  /*chrome 20+*/
  -ms-flex-align: center;
  align-items: center;
  margin-bottom: 0;
  font-size: 1rem;
  font-weight: 400;
  line-height: 1.5;
  color: #495057;
  text-align: center;
  white-space: nowrap;
  background-color: #e9ecef;
  border: 1px solid #ced4da;
  border-radius: 0.25rem;
  border-bottom-right-radius: 0;
  border-top-right-radius: 0;
}

.input-item-text input[type='checkbox'],
.input-item-text input[type='radio'] {
  margin-top: 0;
}

.input-card {
  display: flex;
  flex-direction: column;
  min-width: 0;
  word-wrap: break-word;
  background-color: #fff;
  background-clip: border-box;
  border-radius: 0.25rem;
  width: 22rem;
  border-width: 0;
  border-radius: 0.4rem;
  box-shadow: 0 2px 6px 0 rgba(114, 124, 245, 0.5);
  position: fixed;
  bottom: 1rem;
  right: 1rem;
  -ms-flex: 1 1 auto;
  flex: 1 1 auto;
  padding: 0.75rem 1.25rem;
}

.input-text {
  line-height: 2rem;
  margin-right: 2rem;
}

.info hr {
  margin-right: 0;
  margin-left: 0;
  border-top-color: grey;
}

.info {
  padding: 0.75rem 1.25rem;
  margin-bottom: 1rem;
  border-radius: 0.25rem;
  position: fixed;
  top: 1rem;
  background-color: white;
  width: auto;
  min-width: 22rem;
  border-width: 0;
  right: 1rem;
  box-shadow: 0 2px 6px 0 rgba(114, 124, 245, 0.5);
}

.code {
  left: 1.5rem;
  right: 1.5rem;
  top: 1.5rem;
  bottom: 1.5rem;
  overflow: auto;
  margin-bottom: 0rem;
}

.code .btn {
  top: 1rem;
  position: absolute;
  right: 1rem;
}

.code .result {
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 0.5rem;
  padding: 1rem;
  bottom: 1rem;
  position: absolute;
  top: 5.5rem;
  right: 1rem;
  left: 1rem;
  overflow: auto;
}

.code .status {
  color: #80adff;
  display: inline-block;
  font-size: 14px;
}

.code h4 {
  display: inline-block;
  max-width: 20rem;
  margin-right: 1rem;
  margin-bottom: 1rem;
}

select,
input[type='text'],
input[type='date'] {
  display: inline-block;
  width: 100%;
  padding: 0.375rem 1.75rem 0.375rem 0.75rem;
  line-height: 1.5;
  color: #495057;
  vertical-align: middle;
  background: #fff
    url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'%3E%3Cpath fill='%23343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/%3E%3C/svg%3E")
    no-repeat right 0.75rem center;
  background-size: 8px 10px;
  border: 1px solid #ced4da;
  border-radius: 0.25rem;
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
}

input[type='text'],
input[type='date'] {
  background: #fff;
  padding: 0.375rem 0.75rem;
}

select:focus,
input[type='text']:focus,
input[type='date']:focus {
  border-color: #80bdff;
  outline: 0;
  box-shadow: 0 0 0 0.1rem rgba(128, 189, 255, 0.1);
}

.btn:focus {
  outline: 0;
  box-shadow: none;
}

select:focus::-ms-value,
input[type='text']:focus::-ms-value,
input[type='date']:focus::-ms-value {
  color: #495057;
  background-color: #fff;
}

.handle-img-wrapper {
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 4px;
}
.img-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
}
.handle-img-wrapper:hover .img-cover {
  display: block;
}
.handle-img-wrapper i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}

.demo-upload-list {
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 4px;
}
.demo-upload-list img {
  width: 100%;
  height: 100%;
}
.demo-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
}
.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}
.demo-upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
</style>
